﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Data.Common;
using System.Data.Objects.DataClasses;


using MINERP.COM;
using MINERP.MODEL.GroupMember;

namespace MINERP.DAL.GroupMember
{
    public class GroupMemberDAL
    {
        public List<WorkOrderFlowList> GetTask(int userId, OrderFlowListStatus orderFlowListStatus, OrderFlowListStatus orderFlowListStatus2)
        {
            List<WorkOrderFlowList> TaskList = new List<WorkOrderFlowList>();
            using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
            {
                string strESQL = string.Format("it.userid={0} and it.status in {1}", userId, "{" + Convert.ToInt32(orderFlowListStatus) + "," + Convert.ToInt32(orderFlowListStatus2)) + "}";

                ObjectQuery<WorkOrderFlowList> workFlowListInfoList = DataEntites.WorkOrderFlowList.Where(strESQL);
                //foreach (var item in workFlowListInfoList)
                //{
                //    TaskList.Add(item);
                //}
                TaskList = workFlowListInfoList.ToList();
            }
            return TaskList;

        }

        public IList<WorkOrderFlowList> GetTask(int userId, OrderFlowListStatus orderFlowListStatus, DateTime startTime, DateTime endTime)
        {

            int status = (int)orderFlowListStatus;
            using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
            {
                return DataEntites.WorkOrderFlowList.Where(wf => wf.UserId == userId && wf.Status == status && wf.CompletedTime >= startTime && wf.CompletedTime <= endTime).ToList();
            }
        }

        /// <summary>
        /// 取得不等于某个状态的列表
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="notEqualStatus"></param>
        /// <returns></returns>
        public List<WorkOrderFlowList> GetTask(int userid, List<int> notEqualStatusList)
        {
            //int status = (int)notEqualStatus;
            List<WorkOrderFlowList> result;
            //using (newSampleYPDBEntities data = new newSampleYPDBEntities())
            //{
            //result = data.WorkOrderFlowList.Where(wl => wl.UserId == userid && !notEqualStatusList.Contains(wl.Status)).ToList();
            using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
            {
                result = DataEntites.WorkOrderFlowList.Where(wl => wl.UserId == userid).ToList().Where(wlf => !notEqualStatusList.Contains(wlf.Status)).ToList();
            }
            //data.Dispose();
            //}
            return result;

        }

        public ObjectQuery<photoInfo> GetPhotoListByOrderProductId(int orderProductId)
        {
            using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
            {
                return DataEntites.photoInfo.Where(string.Format("it.orderInfo.OrderProductId={0}", orderProductId));
            }
        }

        /// <summary>
        /// 变等待接收为接收
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="orderFlowListStatus">等待接收的状态</param>
        /// <param name="orderFlowListStatus_3">接收状态</param>
        /// <returns>更改成功返加TRUE</returns>
        public bool ReceiveAllTask(int userId, OrderFlowListStatus orderFlowListStatus, OrderFlowListStatus orderFlowListStatus_3)
        {
            string strEsql = string.Format("it.UserId={0} and it.Status={1}", userId, Convert.ToInt32(orderFlowListStatus));
            using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
            {
                ObjectQuery<WorkOrderFlowList> wis = DataEntites.WorkOrderFlowList.Where(strEsql);
                foreach (var item in wis)
                {
                    item.Status = Convert.ToInt32(orderFlowListStatus_3);
                }

                try
                {
                    DataEntites.SaveChanges();
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
        }

        public bool CompleteWork(int orderProductId, OrderFlowListStatus ChangedOrderFlowListStatus, DateTime dateTime, OrderFlowListStatus OriginalStatus)
        {
            //完成工作
            try
            {
                string strESQL = string.Format("it.orderInfo.OrderProductId={0} and it.Status={1}", orderProductId, Convert.ToInt32(OriginalStatus));
                using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
                {
                    //WorkOrderFlowList workFlowListInfo = DataEntites.WorkOrderFlowList.Where(strESQL).First();//当前结点  
                    //string strESQLNext = string.Format("it.orderInfo.OrderProductId={0} and it.Status={1} and it.WorkOrder>{2}", orderProductId, Convert.ToInt32(OriginalStatus), workFlowListInfo.WorkOrder);

                    WorkOrderFlowList workFlowListInfo = DataEntites.orderInfo.FirstOrDefault(o => o.OrderProductId == orderProductId).WorkOrderFlowList.ToList().FirstOrDefault(wfl => wfl.Status == 1 || wfl.Status == 2);
                    workFlowListInfo.Status = Convert.ToInt32(ChangedOrderFlowListStatus);
                    workFlowListInfo.CompletedTime = dateTime;
                    DataEntites.SaveChanges();

                    string strESQLNext = string.Format("it.orderInfo.OrderProductId={0} and it.Status={1} ", orderProductId, Convert.ToInt32(OrderFlowListStatus.Wait));

                    WorkOrderFlowList NextWorkFlowListInfo = DataEntites.WorkOrderFlowList.Where(strESQLNext).OrderBy("it.WorkOrder").FirstOrDefault();//下一个结点

                    if (NextWorkFlowListInfo != null)
                    {
                        NextWorkFlowListInfo.AssignTime = dateTime;
                        NextWorkFlowListInfo.Status = Convert.ToInt32(OrderFlowListStatus.Useable);//更新下一个节点的状态

                        DataEntites.SaveChanges();
                    }
                }

            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 从photoInfo表中删除此产品下的所有照片
        /// </summary>
        /// <param name="orderProductId"></param>
        public photoInfo DeletePhotoByOrderProductId(int orderProductId, newSampleYPDBEntities DataEntites)
        {
            photoInfo pi = null;
            //using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
            //{
            foreach (var item in DataEntites.photoInfo.Where(string.Format("it.orderInfo.OrderProductId={0}", orderProductId)).ToList())
            {
                if (pi == null)
                {
                    //if (!item.paperFaceReference.IsLoaded)
                    //{
                    //    item.paperFaceReference.Load();
                    //}
                    //if (!item.paperTypeReference.IsLoaded)
                    //{
                    //    item.paperTypeReference.Load();
                    //}
                    pi = item;
                }
                DataEntites.DeleteObject(item);

            }
            //foreach (var item in DataEntites.photoInfo.Where(string.Format("it.orderInfo.OrderProductId={0}", orderProductId)))
            //{
            //    if (pi == null)
            //    {
            //        if (!item.paperFaceReference.IsLoaded)
            //        {
            //            item.paperFaceReference.Load();
            //        }
            //        if (!item.paperTypeReference.IsLoaded)
            //        {
            //            item.paperTypeReference.Load();
            //        }
            //        pi = item;
            //    }
            //    DataEntites.DeleteObject(item);
            //}

            DataEntites.SaveChanges();
            //}
            return pi;
        }

        /// <summary>
        /// 添加新图片
        /// </summary>
        /// <param name="_ImportPicList"></param>
        //public void AddNewPic(List<BigPicInfo> _ImportPicList, photoInfo OldInfo,int orderProductId)
        //{
        //List<photoInfo> addPicList = new List<photoInfo>();
        //foreach (var item in _ImportPicList)
        //{
        //    photoInfo pi = new photoInfo();
        //    pi.photoName = item.PicName;
        //    pi.picPath = item.PicPath;
        //    pi.pixHeight = item.PixHeight;
        //    pi.pixWidth = item.PixWidth;
        //    pi.Remark = item.PicName;
        //    pi.status = Convert.ToInt32(OrderFlowListStatus.Complete);
        //    pi.Width = item.Width;
        //    pi.Height = item.Height;
        //    if (OldInfo == null)
        //    {
        //        pi.paperFaceId = 1;
        //        pi.paperTypeID = 1;
        //    }
        //    else
        //    {
        //        pi.paperFaceId = OldInfo.paperFaceId;
        //        pi.paperTypeID = OldInfo.paperTypeID;
        //    }
        //    pi.GuidCode = "";
        //    pi.IsEnable = true;
        //    pi.MD5Code = " ";
        //    pi.OldPicPath = " ";
        //    pi.PhotoBarCode = " ";
        //    pi.printerId = 0;

        //    //OldInfo.orderInfoReference.Load(MergeOption.PreserveChanges);
        //    //pi.orderInfoReference.EntityKey = new System.Data.EntityKey("DataEntites.orderInfo", "OrderProductId", orderProductId);
        //    pi.orderInfo = DataEntites.orderInfo.First(oi => oi.OrderProductId == orderProductId);
        //    DataEntites.AddTophotoInfo(pi);

        //    //pi.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(pi_PropertyChanged);
        //    //pi.EntityKey.e
        //    addPicList.Add(pi);
        //}

        //DataEntites.SaveChanges();//添加

        ////更新
        //foreach (var item in addPicList)
        //{
        //    item.PhotoBarCode = "1" + string.Format("{0:D9}", item.photoID);
        //}
        //DataEntites.SaveChanges();//更新

        ////添加完成
        //}

        void pi_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {

        }

        public string GetRemarkByOrderProductId(int orderProductId)
        {
            string strEsql = string.Format("it.OrderProductId={0}", orderProductId);
            using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
            {
                orderInfo oi = DataEntites.orderInfo.Where(strEsql).Include("Tb_OrderBag").First();

                return oi.Tb_OrderBag.Remark;
            }
        }

        public IQueryable<Tb_OrderBag> GetCtmList(int shopId)
        {
            using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
            {
                return DataEntites.Tb_OrderBag.Where<Tb_OrderBag>(p => p.Shop.ShopId == shopId);
            }
        }

        public void AddNewPic(List<photoInfo> newPigPhotoList, TaskInfo taskInfo, newSampleYPDBEntities DataEntites)
        {
            //using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
            //{
            orderInfo OrderInfo = DataEntites.orderInfo.First(oi => oi.OrderProductId == taskInfo.OrderProductId);
            OrderInfo.Remark = taskInfo.ProductRemark;
            OrderInfo.PageNum = newPigPhotoList.Count;
            foreach (var item in newPigPhotoList)
            {
                OrderInfo.photoInfo.Add(item);
            }
            //将singlePageNum暂时用做设计的张数
            //OrderInfo.SinglePageNum = newPigPhotoList.GroupBy(pi => pi.picPath).Count();
            DataEntites.SaveChanges();//添加


            //更新
            foreach (var item in newPigPhotoList)
            {
                item.PhotoBarCode = "3" + string.Format("{0:D9}", item.photoId);
            }
            DataEntites.SaveChanges();//更新barCode
            //}
        }

        /// <summary>
        /// 改变状态
        /// </summary>
        /// <param name="OrderProductId">orderinfo的ID</param>
        /// <param name="orderFlowListStatus">oldstatus</param>
        /// <param name="orderFlowListStatus_3">new status</param>
        public void ModifyStatus(int OrderProductId, OrderFlowListStatus originalStatus, OrderFlowListStatus newStatus)
        {
            using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
            {
                orderInfo oi = DataEntites.orderInfo.Where(o => o.OrderProductId == OrderProductId).First();
                if (!oi.WorkOrderFlowList.IsLoaded)
                {
                    oi.WorkOrderFlowList.Load();
                }
                WorkOrderFlowList wfl = oi.WorkOrderFlowList.Where(p => p.Status == (int)originalStatus).FirstOrDefault();

                //WorkOrderFlowList wfl = DataEntites.WorkOrderFlowList.Where(p => p.orderInfo.OrderProductId == oi.OrderProductId && p.Status == (int)originalStatus).FirstOrDefault();
                if (wfl != null)
                {
                    wfl.Status = (int)newStatus;
                    DataEntites.SaveChanges();
                }
            }
        }


        public Tb_Product GetProuctByOrderInfoId(int orderProductId)
        {
            using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
            {
                orderInfo oi = DataEntites.orderInfo.Where(o => o.OrderProductId == orderProductId).First();
                if (!oi.Tb_ProductReference.IsLoaded)
                {
                    oi.Tb_ProductReference.Load();
                }
                return oi.Tb_Product;
            }
        }
    }
}
